package com.example.studentdemo.common;

import cn.hutool.core.util.StrUtil;
import com.example.studentdemo.entity.Account;
import com.example.studentdemo.exception.CustomerException;
import com.example.studentdemo.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头拿到token
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            // 如果没拿到，再从参数拿一次
            token = request.getParameter("token");
        }
        // 认证token
        if (StrUtil.isBlank(token)) {
            throw new CustomerException("401", "您无权限操作");
        }

        // 使用TokenUtils验证token
        if (TokenUtils.verifyToken(token)) {
            throw new CustomerException("401", "您无权限操作");
        }

        // 获取当前用户
        Account account = TokenUtils.getCurrentUser();
        if (account == null) {
            throw new CustomerException("401", "您无权限操作");
        }

        return true;
    }
}
